<?php
//首页显示
namespace Home\Controller;
use Think\Controller;
class UserController extends CommonController {
	function _initialize(){
		parent::_initialize();
		$perv_url=$_SERVER['HTTP_REFERER'];
		if(!$perv_url){
			$perv_url="/";
		}
		if(!strpos($perv_url,'register')&&!strpos($perv_url,'login')){
			session('perv_url',$perv_url);
		}
		
		$user_id=session('user_id');
		if($user_id){
			//登录时不允许访问操作
			$agreen_action=array('login','register','login_in','register_in','register_validate','sms_captcha','forget_pwd','verify','forget_pwd_moblie','forget_pwd_yanzheng','forget_pwd_rest');
			$users=M('users');
			$userinfo=$users->find($user_id);
			$this->assign('userinfo',$userinfo);
			$action_name=ACTION_NAME;
			if(in_array($action_name,$agreen_action)){
				$this->redirect('user/center');
			}
		}else{
			//未登录时允许访问操作
			$agreen_action=array('help','help_info','qqlogin','qq_login','oauth_login','weibo','weixin_return','weixin_login','collect','login','register','login_in','register_in','login_out','register_validate','sms_captcha','forget_pwd','verify','forget_pwd_moblie','forget_pwd_yanzheng','forget_pwd_rest','jiemi');
			$action_name=ACTION_NAME;
			if(!in_array($action_name,$agreen_action)){
				$this->redirect('user/login');
			}
		}
	}
    public function index(){
		$this->display();
	}
	public function login(){
		session('step',1);
		$this->display();
	}
	public function register(){
		
		$this->display();
	}
	public function forget_pwd(){
		if($_POST){
			$data=I('post.');
			$captcha=$data['captcha'];
			$verify = new \Think\Verify();    
			$res= $verify->check($captcha, 1);
			if($res){
				$users=M('users');
				$rs=$users->where('phone="'.$data['mobile'].'" and ishidden=1')->find();
				if($rs){
					session('forget_user',$data['mobile']);
					session('step','2');
					$this->ajax_r(1,'','验证成功！');
				}else{
					$this->ajax_r(0,'','用户不存在！');
				}
			}else{
				$this->ajax_r(0,'','验证码错误！');
			}
		}else{
			$step=$_GET['step']?$_GET['step']:1;
			if(session('step')!=$step&&session('step')){
				$this->redirect('user/forget_pwd',array('step'=>session('step')));
			}
			$this->display();
		}
		
	}
	public function forget_pwd_moblie(){
		$moblie=session('forget_user');
		if($moblie){
			$code=rand(1000,9999);
			$rs=duanxin($code,$moblie);
			if($rs['resultcode']==0){
				session('forget_pwd_code',$code);
				$this->ajax_r(1,'','发送成功！');
			}else{
				$this->ajax_r(0,$rs['errordescription'],'发送失败！');
			}
			
		}else{
			$this->ajax_r(0,'','验证手机不存在,请重新验证！');
		}
		
	}
	public function forget_pwd_rest(){
		$moblie=session('forget_user');
		if($moblie){
			$pwd=I('post.pwd');
			
			$data['password']=passport_encrypt($pwd,'wnsc');
			$users=M('users');
			
			$rs=$users->where("phone=$moblie")->save($data);
			if($rs){
				session('step','4');
				session('forget_user',null);
				session('forget_pwd_code',null);
				$this->ajax_r(1,$rs,'密码重置成功！');
			}else{
				$this->ajax_r(0,$rs,'密码重置失败！');
			}
		}else{
			$this->ajax_r(0,'','验证手机不存在,请重新验证！');
		}
	}
	public function forget_pwd_yanzheng(){
		if($_POST){
			$moblie=session('forget_user');
			if($moblie){
				$sms_captcha=I('post.sms_captcha');
				if($sms_captcha==session('forget_pwd_code')){
					session('step','3');
					$this->ajax_r(1,'','验证成功！');
				}else{
					$this->ajax_r(0,'','验证失败！');
				}
			}else{
				$this->ajax_r(2,'','验证手机不存在,请重新验证！');
			}
		}
	}
	public function verify(){
	    $config =   array(
	            'fontSize'  =>  16,              // 验证码字体大小(px)
	            'useNoise'=>false,
	            'useCurve'=>false,
	            'length'=>4
	              
	    );
	    $verify = new \Think\Verify($config);
	    $verify->entry(1);
	}
	public function login_in(){
		if($_POST){
			$users=M('users');
			$data=I('post.');
			$phone=$data['phone'];
			$password=$data['password'];
			$userinfo=$users->where('phone="'.$phone.'"')->find();
			if($userinfo){
				$pass=passport_decrypt($userinfo['password'],'wnsc');
				if($pass==$password){
					
					
					session('user_id',$userinfo['id']);
					session('user_name',$userinfo['username']);
					session('user_pic',$userinfo['user_pic']);
					session('login_time',$userinfo['login_time']);
					//更新登录时间
					$date_time=date('Y-m-d H:i:s', time());
					$login_info['id']=$userinfo['id'];
					$login_info['login_time']=$date_time;
					$users->save($login_info);
					
					if($data['rememberMe']==1){
						cookie('user_id',$userinfo['id'],3600*24*7);
           				cookie('user_name',$userinfo['username'],3600*24*7);
					}
					$perv_url=session('perv_url');
					//添加cookie 购物车
					$cart_array = cookie('cart_array');
					$cart_array = json_decode($cart_array,true);
					foreach($cart_array as $key => $v){
						addcart($userinfo['id'],$v['shop_id'],$v['sku_id'],$v['num']);
					}
					cookie('cart_array',null);
					$this->ajax_r(1,$perv_url,'登录成功！');
				}else{
					$this->ajax_r(0,$password,'密码错误！');
				}
			}else{
				$rs=wunen_register($phone,$password);
				$rs=json_decode($rs,true);
				if($rs['success']){
					$info['username']=$phone;
					$info['phone']=$phone;
					$info['password']=passport_encrypt($password,'wnsc');
					$info['addtime']=time();
					$date_time=date('Y-m-d H:i:s', time());
					$info['login_time']=$date_time;
					$rs=$users->add($info);
					$userinfo=$users->where('phone="'.$phone.'"')->find();
					session('user_id',$userinfo['id']);
					session('user_name',$userinfo['username']);
					session('user_pic',$userinfo['user_pic']);
					session('login_time',$userinfo['login_time']);
					//更新登录时间
					$date_time=date('Y-m-d H:i:s', time());
					$login_info['id']=$userinfo['id'];
					$login_info['login_time']=$date_time;
					$users->save($login_info);
					if($data['rememberMe']==1){
						cookie('user_id',$userinfo['id'],3600*24*7);
           				cookie('user_name',$userinfo['username'],3600*24*7);
					}
					$perv_url=session('perv_url');
					//添加cookie 购物车
					$cart_array = cookie('cart_array');
					$cart_array = json_decode($cart_array,true);
					foreach($cart_array as $key => $v){
						if($v['recommend_id']&&$v['recommend_id']!=$userinfo['id']){
							addcart($userinfo['id'],$v['shop_id'],$v['sku_id'],$v['num'],'','',$v['recommend_id']);
						}else{
							addcart($userinfo['id'],$v['shop_id'],$v['sku_id'],$v['num']);
						}
						
					}
					cookie('cart_array',null);
					
					$this->ajax_r(1,$perv_url,'登录成功！');
				}else{
					$this->ajax_r(0,'','该用户不存在！');
				}
				
			}
			
			
		}
	}
	public function register_in(){
		if($_POST){
			$users=M('users');
			$data=I('post.');
			$moblie=$data['mobile'];
			$password=$data['password'];
			$sms_captcha=$data['sms_captcha'];
			$code=session('moblie_code');
			
			if($code){
				if($code==$sms_captcha){
					$info['username']=$moblie;
					$info['phone']=$moblie;
					$info['password']=passport_encrypt($password,'wnsc');
					$info['addtime']=time();
					$date_time=date('Y-m-d H:i:s', time());
					$info['login_time']=$date_time;
					$rs=$users->add($info);
					if($rs){
						session('user_id',$rs);
						session('user_name',$info['username']);
						$perv_url=session('perv_url');
						$this->ajax_r(1,$perv_url,'注册成功');
					}
				}else{
					$this->ajax_r(0,'','短信验证码错误');
				}
			}else{
				$this->ajax_r(0,'','短信验证码失效');
			}
			
		}
	}
	public function login_out(){
		session('user_id',null);
		session('user_name',null);
		cookie('user_id',null);
		cookie('user_name',null);
		$perv_url=$_SERVER['HTTP_REFERER'];
		echo "<script language='javascript' type='text/javascript'>";
		echo "window.location.href='".$perv_url."'";
		echo "</script>";
		
	}
	public function register_validate(){
		$data=I('get.');
		$users=M('users');
		$moblie=$data['MobileRegisterModel']['mobile'];
		if(!$moblie){
			$moblie=$data['mobile'];
		}
		$rs=$users->where('phone="'.$moblie.'" and ishidden=1')->find();
		if($rs){
			$this->ajax_r(1,'','该帐号已注册');
		}else{
			$this->ajax_r(0,'','');
		}
		
	}
	public function sms_captcha(){
		$data=I('post.');
		$moblie=$data['mobile'];
		$code=rand(1000,9999);
		$rs=duanxin($code,$moblie);
		if($rs['resultcode']==0){
			session('moblie_code',$code);
			$this->ajax_r(1,'','发送成功！');
		}else{
			$this->ajax_r(0,$rs['errordescription'],'发送失败！');
		}
	}
	
	public function sms_captcha2(){
		$data=I('post.');
		$moblie=$data['mobile'];
		$code=rand(1000,9999);
		$rs=duanxin($code,$moblie);
		if($rs['resultcode']==0){
			session('bd_moblie_code',$code);
			$this->ajax_r(1,'','发送成功！');
		}else{
			$this->ajax_r(0,$rs['errordescription'],'发送失败！');
		}
	}
	
	public function sms_captcha_ali(){
		$data=I('post.');
		$moblie=$data['mobile'];
		$code=rand(1000,9999);
		$rs=duanxin($code,$moblie);
	
		if($rs['resultcode']==0){
			session('moblie_ali_code',$code);
			$this->ajax_r(1,'','发送成功！');
		}else{
			$this->ajax_r(0,$rs['errordescription'],'发送失败！');
		}
	}
	//解密
	public function jiemi(){
		$password=I('get.pass');
		$pass=passport_decrypt($password,'wnsc');
		var_dump($pass);
	}
	
	public function center(){
		if(session('user_id')){
			$uid=session('user_id');
			$shop=M('shop');
			$shop_sku=M('shop_sku');
			$order=M('order');
			$order_goods=M('order_goods');
			//红包
			$daiyan=get_userdaiyan_list($uid);
			$daiyan_price=0;
			foreach($daiyan as $key=>$value){
				$daiyan_price=$daiyan_price+$value['recommend_price'];
			}
			$this->assign('daiyan_price',$daiyan_price);
			
			$coupon=M('coupon');
			$coupon_list=$coupon
    			->field('yt_coupon_type.*')
    			->join('yt_coupon_type on yt_coupon_type.coupon_type_id =yt_coupon.coupon_type_id')
    			->where("yt_coupon.uid=$uid")
    			->count();
    		$this->assign('coupon_list',$coupon_list);
	    	//未付款
	    	$wcount=$order->where('buyer_id='.$uid.' and order_state="10" and refund_state=0 and tuanselect=0')->count();
	    	//已付款待发货
	    	$dfcount=$order->where('buyer_id='.$uid.' and order_state="20" and refund_state=0 and tuanselect=0')->count();
	 
	    	//已发货待收货
	    	$dscount=$order->where('buyer_id='.$uid.' and order_state="30" and refund_state=0 and tuanselect=0')->count();
	    	$this->assign('wcount',$wcount);
	    	$this->assign('dfcount',$dfcount);
	    	$this->assign('dscount',$dscount);
			//订单列表
			$order_goods_list=$order_goods->where('buyer_id='.$uid)->limit(4)->order('rec_id desc')->select();
			$this->assign('order_goods_list',$order_goods_list);
			
			//购物车
			$cart=M('cart');
			$cart_list=$cart->where('buyer_id='.$uid)->limit(4)->select();
			$cart_info;
			foreach($cart_list as $key => $v){
				
				$cart_info[$key]['num']=$v['num'];
				$cart_info[$key]['price']=$v['price'];
				$cart_info[$key]['shop_picture']=$v['shop_picture'];
				if($v['sku_id']!=0){
					$rs_shop_sku=$shop_sku->where('sku_id='.$v['sku_id'])->find();
					$cart_info[$key]['shop_name']=$v['shop_name'].'&nbsp;'.$rs_shop_sku['sku_spec'].'&nbsp;'.$rs_shop_sku['sku_style'];
				}else{
					$cart_info[$key]['shop_name']=$v['shop_name'];
				}
				$cart_info[$key]['url']=U('shop/index',array('id'=>$v['shop_id']));
				$cart_info[$key]['id']=$v['shop_id'].','.$v['sku_id'];
				
			}
			//店铺收藏
			$users_storecollect=M('users_storecollect');
			$rs_store=$users_storecollect
				->field('yt_store.title,yt_store.id,yt_store.id,yt_store_template.portrait')
				->join('yt_store ON yt_store.id = yt_users_storecollect.shore_id','left')
				->join('yt_store_template ON yt_store_template.store_id = yt_users_storecollect.shore_id','left')
				->where('yt_users_storecollect.user_id='.$uid)
				->limit(6)
				->order('yt_users_storecollect.addtime desc')
				->select();
			//商品收藏
			$users_shopcollect=M('users_shopcollect');
			$rs_shop=$users_shopcollect
				->field('yt_shop.title,yt_shop.id,yt_shop.price,yt_shop.image')
				->join('yt_shop ON yt_shop.id = yt_users_shopcollect.shop_id','left')
				->where('yt_users_shopcollect.user_id='.$uid)
				->order('yt_users_shopcollect.addtime desc')
				->limit(6)
				
				->select();
			//历史记录
			$users_shophistory=M('users_shophistory');
			$rs_history=$users_shophistory
				->field('yt_shop.title,yt_shop.id,yt_shop.price,yt_shop.image')
				->join('yt_shop ON yt_shop.id = yt_users_shophistory.shop_id','left')
				->where('yt_users_shophistory.user_id='.$uid)
				->limit(6)
				->order('yt_users_shophistory.addtime desc')
				->select();
			
		}
		$this->assign('cart_info',$cart_info);
		$this->assign('rs_store',$rs_store);
		$this->assign('rs_shop',$rs_shop);
		$this->assign('rs_history',$rs_history);
		
		$this->display();
	}
	//收藏 type=1 为商品 2为店铺
	public function collect(){
		$user_id=session('user_id');
		if($_POST&&$user_id){
			$data=I('post.');
			if($data['type']==1&&$data['id']){
				$newdata['shop_id']=$data['id'];
				$newdata['user_id']=$user_id;
				$users_shopcollect=M('users_shopcollect');
				$rs=$users_shopcollect->where($newdata)->select();
				if($rs){
					$this->ajax_r(0,'','该商品已收藏！');
				}else{
					$newdata['addtime']=time();
					$rs=$users_shopcollect->add($newdata);
					$this->ajax_r(1,'','收藏成功！');
				}
			}
			if($data['type']==2){
				$newdata['shore_id']=$data['id'];
				$newdata['user_id']=$user_id;
				$users_storecollect=M('users_storecollect');
				$rs=$users_storecollect->where($newdata)->select();
				if($rs){
					$this->ajax_r(0,'','该店铺已收藏！');
				}else{
					$newdata['addtime']=time();
					$rs=$users_storecollect->add($newdata);
					$this->ajax_r(1,'','收藏成功！');
				}
			}
		}else{
			$this->ajax_r(0,'','请先登录！');
		}
	}
	//取消收藏 type=1 为商品 2为店铺
	public function delcollect(){
		$user_id=session('user_id');
		if($_POST&&$user_id){
			$data=I('post.');
			if($data['type']==1&&$data['id']){
				$newdata['shop_id']=$data['id'];
				$newdata['user_id']=$user_id;
				$users_shopcollect=M('users_shopcollect');
				$rs=$users_shopcollect->where($newdata)->delete();
				if($rs){
					$this->ajax_r(0,'','删除成功！');
				}else{
					$this->ajax_r(0,'','收藏失败！');
				}
			}
			if($data['type']==2){
				$newdata['shore_id']=$data['id'];
				$newdata['user_id']=$user_id;
				$users_storecollect=M('users_storecollect');
				$rs=$users_storecollect->where($newdata)->delete();
				if($rs){
					$this->ajax_r(0,'','删除成功！');
				}else{
					$this->ajax_r(0,'','收藏失败！');
				}
			}
		}
	}
	public function info(){
		$users=M('users');
		$user_id=session('user_id');
		if($_POST){
			$data=I('post.');
			if($data['act']=='act_edit_profile'){
				$data['id']=$user_id;
				$rs=$users->save($data);
				if($rs){
					$this->ajax_r(0,'','修改成功！');
				}else{
					$this->ajax_r(0,'','未更新数据！');
				}
			}
			if($data['act']=='act_edit_img'){
				$info['id']=$user_id;
				$info['user_pic']=$data['UpFilePathInfo'];
				$rs=$users->save($info);
				if($rs){
					$this->ajax_r(0,'','修改成功！');
				}else{
					$this->ajax_r(0,'','未更新数据！');
				}
			}
		}else{
			$this->display();
		}
	}
	
	public function address(){
		$user_id=session('user_id');
		$users_address=M('users_address');
		$countdefault=$users_address->where('is_default=1 and user_id='.$user_id)->count();
		if($countdefault!=1){
			$users_address-> where('user_id='.$user_id)->setField('is_default',0);
			$first=$users_address->order('address_id asc')->limit(1)->find();
			$users_address-> where('address_id='.$first['address_id'])->setField('is_default',1);
		}
		$count=$users_address->where('user_id='.$user_id)->count();
		$Page = new \Think\Page ($count, 10 ); // 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
		$show = $Page->show(); // 分页显示输出
		
		$address=$users_address->where('user_id='.$user_id)->limit($Page->firstRow.','.$Page->listRows)->select();
		foreach($address as $key=>$value){
			$province=getProvinceInfo($value['province']);
			$city=getCityInfo($value['city']);
			$district=getDistrictInfo($value['district']);
			$address[$key]['province']=$province['province_name'];
			$address[$key]['city']=$city['city_name'];
			$address[$key]['district']=$district['district_name'];
		}
		$this->assign('page', $show ); // 赋值分页输出
		$this->assign('count',$count);
		$this->assign('address',$address);
		$this->display();
	}	
	
	public function addressInsert(){
		$user_id=session('user_id');
		$users_address=M('users_address');
		if($_POST){
			$users_address-> where('user_id='.$user_id)->setField('is_default',0);
			$data=I('post.');
			$data['user_id']=$user_id;
			$data['is_default']=1;
			$rs=$users_address->add($data);
			if($rs){
				$this->ajax_r('1','','添加成功');
			}else{
				$this->ajax_r('0','','添加失败');
			}
		}else{
			$id=I('get.id');
			$rs=$users_address->find($id);
			$this->assign('rs',$rs);
			$this->display();
		}
		
	}
	
	public function get_user_address(){
		$id=I('post.id');
		$users_address=M('users_address');
		$rs=$users_address->find($id);
		$this->ajax_r('1',$rs,'地址信息！');
	}
	public function addressisdefault(){
		$address_id=I('get.id');
		$user_id=session('user_id');
		$users_address=M('users_address');
		$users_address-> where('user_id='.$user_id)->setField('is_default',0);
		$users_address-> where('address_id='.$address_id)->setField('is_default',1);
		if(I('get.type')==1){
			$this->ajax_r('1','','设置默认成功');
		}else{
			$this->redirect('user/address');
		}
		
	}
	public function updateMemberAddress(){
		$user_id=session('user_id');
		$users_address=M('users_address');
		if($_POST){
			$data=I('post.');
			$data['user_id']=$user_id;
			$rs=$users_address->save($data);
			if($rs){
				$this->ajax_r('1','','修改成功');
			}else{
				$this->ajax_r('0','','修改失败');
			}
		}
	}		
	
	public function addressdelete(){
		$id=I('post.id');
		$users_address=M('users_address');
		$rs=$users_address->delete($id);
		if($rs){
			$this->ajax_r('1','','删除成功');
		}else{
			$this->ajax_r('0','','删除失败');
		}
	}
	 public function uploadify_wb()
    {
        if(I('get.isthumb')){
            $width  =   I('get.width','400');
            $height =   I('get.height','400');
        }else{
            $width  =   I('get.width');
            $height =   I('get.height');
        }
        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $upload = new \Think\Upload();
            $upload->maxSize = 2048000;
            $upload->allowExts = array('jpg','jpeg','gif','png','xls');
            $upload->savePath = "/";
            $upload->thumb = true; //设置缩略图
            $upload->imageClassPath = "@.ORG.Image";
            $upload->saveRule = uniqid; //上传规则
            $upload->thumbRemoveOrigin = true; //删除原图
            $info   =   $upload->upload();
            if(!$info) {
                echo 'error'.$upload->getError();// 上传错误提示错误信息
            }else{
                foreach($info as $file){
                    $path='/Uploads'.$file['savepath'].$file['savename'];
                    $name   =   $_SERVER["DOCUMENT_ROOT"].$path;
                    $imageArray =   getimagesize($name);
                    if( ( $width || $height ) && ( $imageArray[0] > $width || $imageArray[1] > $height ) ){
                        $save_path=$_SERVER['DOCUMENT_ROOT'].$path;
                        $thumb_path=$_SERVER['DOCUMENT_ROOT'].'/Uploads'.$file['savepath'].'thumb_'.$file['savename'];
                        $image = new \Think\Image(); 
                        $image->open($save_path);
                        $image->thumb($width, $height)->save($save_path);
                    }
                    
                }
            }
           
            $data['saveURL']=$path;
            $data['state']='success';
            $data['status']=1;
            $this->ajaxReturn($data);

        }
    }
    
     public function uploadify_wb2()
    {
        if(I('get.isthumb')){
            $width  =   I('get.width','400');
            $height =   I('get.height','400');
        }else{
            $width  =   I('get.width');
            $height =   I('get.height');
        }
        if (!empty($_FILES)) {
            import("@.ORG.UploadFile");
            $upload = new \Think\Upload();
            $upload->maxSize = 2048000;
            $upload->allowExts = array('jpg','jpeg','gif','png','xls');
            $upload->savePath = "/";
            $upload->thumb = true; //设置缩略图
            $upload->imageClassPath = "@.ORG.Image";
            $upload->saveRule = uniqid; //上传规则
            $upload->thumbRemoveOrigin = true; //删除原图
            $info   =   $upload->upload();
            if(!$info) {
                echo 'error'.$upload->getError();// 上传错误提示错误信息
            }else{
                foreach($info as $file){
                    $path='/Uploads'.$file['savepath'].$file['savename'];
                    $name   =   $_SERVER["DOCUMENT_ROOT"].$path;
                    $imageArray =   getimagesize($name);
                    if( ( $width || $height ) && ( $imageArray[0] > $width || $imageArray[1] > $height ) ){
                        $save_path=$_SERVER['DOCUMENT_ROOT'].$path;
                        $thumb_path=$_SERVER['DOCUMENT_ROOT'].'/Uploads'.$file['savepath'].'thumb_'.$file['savename'];
                        $image = new \Think\Image(); 
                        $image->open($save_path);
                        $image->thumb($width, $height)->save($save_path);
                    }
                    
                }
            }
           echo $path;
           

        }
    }
    
    function del_img(){
    	if($_POST){
    		$imgsrc=I('post.imgsrc');
    		$path = $_SERVER['DOCUMENT_ROOT'].$imgsrc;
			unlink($path);
    		
    	}
    }
     /**
     * 获取省列表
     */
    public function getProvince()
    {
    	$province_list = getProvinceList();
    	$this->ajaxReturn($province_list);
    }


    /**
     * 获取城市列表
     *
     * @return Ambigous <multitype:\think\static , \think\false, \think\Collection, \think\db\false, PDOStatement, string, \PDOStatement, \think\db\mixed, boolean, unknown, \think\mixed, multitype:, array>
     */
    public function getCity()
    {
        
        $province_id = isset($_POST['province_id']) ? $_POST['province_id'] : 0;
        $city_list = getCityList($province_id);
        $this->ajaxReturn($city_list);
       
    }

    /**
     * 获取区域地址
     */
    public function getDistrict()
    {
       
        $city_id = isset($_POST['city_id']) ? $_POST['city_id'] : 0;
        $district_list = getDistrictList($city_id);
        $this->ajaxReturn($district_list);
       
    }

    /**
     * 获取选择地址
     *
     * @return unknown
     */
    public function getSelectAddress()
    {

        $province_list = getProvinceList();
        $province_id = isset($_POST['province_id']) ? $_POST['province_id'] : 0;
        $city_id = isset($_POST['city_id']) ? $_POST['city_id'] : 0;
        $city_list = getCityList($province_id);
        $district_list =getDistrictList($city_id);
        $data["province_list"] = $province_list;
        $data["city_list"] = $city_list;
        $data["district_list"] = $district_list;
         $this->ajaxReturn($data);
    }	
    
    public function order(){
    	$uid=session('user_id');
    	$order=M('order');
    	//全部
    	$cccount=$order->where('buyer_id='.$uid.'and refund_state=0 and tuanselect=0')->count();
    	//未付款
    	$wcount=$order->where('buyer_id='.$uid.' and order_state="10" and refund_state=0 and tuanselect=0 ')->count();
    	//已付款待发货
    	$dfcount=$order->where('buyer_id='.$uid.' and order_state="20" and refund_state=0 and tuanselect=0')->count();
    	//已发货待收货
    	$dscount=$order->where('buyer_id='.$uid.' and order_state="30" and refund_state=0 and tuanselect=0' )->count();
    	//待评价
    	$dpcount=$order->where('buyer_id='.$uid.' and evaluation_state="0" and refund_state=0 and order_state="40"')->count();
    	$where['buyer_id']=$uid;
    	$where['tuanselect']='0';
       
    	if(I('get.stauts')==1){
    		$where['order_state']='10';
            $where['refund_state']='0';
    	}
    	if(I('get.stauts')==2){
    		$where['order_state']='20';
            $where['refund_state']='0';
    	}
    	if(I('get.stauts')==3){
    		$where['order_state']='30';
            $where['refund_state']='0';
    	}
    	if(I('get.stauts')==4){
    		$where['order_state']='40';
    		$where['evaluation_state']='0';
    	}
    	$count=$order->where($where)->count();
		$Page = new \Think\Page ($count,4); // 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
		$show = $Page->show(); // 分页显示输出
		$order_list=$order->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('order_id desc')->select();
    	$this->assign('order_list',$order_list);
    	$this->assign('page',$show);
    	$this->assign('count',$count);
    	$this->assign('wcount',$wcount);
    	$this->assign('dfcount',$dfcount);
    	$this->assign('dscount',$dscount);
    	$this->assign('dpcount',$dpcount);
    	$this->assign('cccount',$cccount);
    	$this->display();
    }

    public function crowdfunding(){
        $uid=session('user_id');
        $order=M('order');

        $ccount=$order
            ->field("yt_order.*,yt_order_goods.goods_id,yt_order_goods.goods_name,yt_order_goods.goods_price,yt_order_goods.goods_image")
            ->join('yt_order_goods ON yt_order.order_id = yt_order_goods.order_id','left')
            ->where("yt_order.buyer_id=$uid and yt_order_goods.goods_id in (SELECT goods_id from yt_crowdfunding) and (yt_order.order_state='20' or yt_order.order_state='30'or yt_order.order_state='40')")
            ->count();
        $wcount=$order
            ->field("yt_order.*,yt_order_goods.goods_id,yt_order_goods.goods_name,yt_order_goods.goods_price,yt_order_goods.goods_image")
            ->join('yt_order_goods ON yt_order.order_id = yt_order_goods.order_id','left')
            ->where("yt_order.buyer_id=$uid and yt_order_goods.goods_id in (SELECT goods_id from yt_crowdfunding) and yt_order.order_state='10'")
            ->count();
        $this->assign('ccount',$ccount);
        $this->assign('wcount',$wcount);
        /*if(I('get.stauts')==1){
            //已支付
            $where="(yt_order.order_state='20' or yt_order.order_state='30'or yt_order.order_state='40')";
        }else*/
        if(I('get.stauts')==2){
            //未付款
            $where="yt_order.order_state='10'";
        }else{
            $where="(yt_order.order_state='20' or yt_order.order_state='30'or yt_order.order_state='40')";
		}
        $count=$order
            ->field("yt_order.*,yt_order_goods.goods_id,yt_order_goods.goods_name,yt_order_goods.goods_price,yt_order_goods.goods_image")
            ->join('yt_order_goods ON yt_order.order_id = yt_order_goods.order_id','left')
            ->where("yt_order.buyer_id=$uid and yt_order_goods.goods_id in (SELECT goods_id from yt_crowdfunding) and ".$where)
            ->count();
        $Page = new \Think\Page ($count,4); // 实例化分页类 传入总记录数
        $Page->setConfig('header','条记录');
        $Page->setConfig('prev','上一页');
        $Page->setConfig('next','下一页');
        $show = $Page->show(); // 分页显示输出

        $order_list=$order
            ->field("yt_order.*,yt_order_goods.goods_id,yt_order_goods.goods_name,yt_order_goods.goods_price,yt_order_goods.goods_image")
            ->join('yt_order_goods ON yt_order.order_id = yt_order_goods.order_id','left')
            ->where("yt_order.buyer_id=$uid and yt_order_goods.goods_id in (SELECT goods_id from yt_crowdfunding) and ".$where)
            ->limit($Page->firstRow.','.$Page->listRows)
            ->order('yt_order.order_id desc')
            ->select();
        $crowdfunding=M('crowdfunding');
        if($order_list){
        	foreach ($order_list as $key=>$val){
                 $goods_id=$val['goods_id'];
                 $crowdfundingDetails=$crowdfunding->where("goods_id=".$goods_id)->select();
                $order_list[$key]['crowdfunding_id']=$crowdfundingDetails['0']['id'];
			}
		}
		//print_r($order->getLastSql());
        //print_r($order_list);
        //print_r($order_list);
        $this->assign('order_list',$order_list);
        $this->assign('page',$show);
        $this->display();
    }
      public function order_pt(){
    	$uid=session('user_id');
    	$order=M('order');
    	$status=I('get.stauts',0);
    	//全部
    	$cccount=$order->where('buyer_id='.$uid.' and tuanselect=1 and order_state>="10"')->count();
    	//等待拼团
    	$wcount=$order->where('buyer_id='.$uid.' and order_state<="20" and order_state>="10" and refund_state=0 and tuanselect=1 and tuan_is_success=0')->count();
    	//拼团成功
    	$dfcount=$order->where('buyer_id='.$uid.' and order_state>="20" and refund_state=0 and tuanselect=1 and tuan_is_success=1')->count();
    	//拼团失败
    	$dscount=$order->where('buyer_id='.$uid.' and order_state="20" and refund_state>0 and tuanselect=1 and tuan_is_success=0' )->count();
    	
    	$where['buyer_id']=$uid;
    	$where['tuanselect']='1';
    	if($status==0){
    		$where['order_state']= array('EGT','10');
    	}
    	
    	if($status==1){
    		$where['tuan_is_success']= array('eq',0);
    		$where['order_state']= array('between',array('10','20'));
    	
    		$where['refund_state']='0';
    	}
    	if(I('get.stauts')==2){
    		$where['tuan_is_success']= array('eq',1);
    		$where['order_state']= array('EGT','20');
    		$where['refund_state']='0';
    	}
    	if(I('get.stauts')==3){
    		$where['tuan_is_success'] = array('eq',0);
    		$where['refund_state'] = array('gt',0);
    	}
    	
    	$count=$order->where($where)->count();
		$Page = new \Think\Page ($count,4); // 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
		$show = $Page->show(); // 分页显示输出
		$order_list=$order->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('order_id desc')->select();
    	$this->assign('order_list',$order_list);
    	$this->assign('page',$show);
    	$this->assign('count',$count);
    	$this->assign('wcount',$wcount);
    	$this->assign('dfcount',$dfcount);
    	$this->assign('dscount',$dscount);
    	$this->assign('dpcount',$dpcount);
    	$this->assign('cccount',$cccount);
    	$this->display();
    }
    
    
    public function order_info(){
    	
    	$uid=session('user_id');
    	if(I('get.id')){
    		$order_id=I('get.id');
           // print_r($_GET);
            $crowdfunding_id=I('get.cid');
	    	$order=M('order');
	    	$order_goods=M('order_goods');
	    	$order_info=$order->where('buyer_id='.$uid.' and order_id='.$order_id)->find();
	    	$order_goods_info=$order_goods->where('order_id='.$order_id)->select();
	    	$youhui_price=get_coupon_price($order_info['buyer_id'],$order_info['coupon']);
            $this->assign('crowdfunding_id',$crowdfunding_id);
	    	$this->assign('order_goods_info',$order_goods_info);
	    	$this->assign('order_info',$order_info);
	    	$this->assign('order_num',$order_info['order_sn']);
	    	$this->assign('youhui_price',$youhui_price);
	    	$this->display();
    	}
    	if(I('get.order')){
    		$order_num=I('get.order');
	    	$order=M('order');
	    	$order_goods=M('order_goods');
	    	$order_info_s=$order->where("buyer_id=$uid and order_cn='$order_num'")->select();
	   
	    	$order_info_d=$order->where('buyer_id='.$uid.' and order_sn='.$order_num)->find();
	    	if($order_info_s){
	    		$order_info=$order->where('buyer_id='.$uid.' and order_id='.$order_info_s[0]['order_id'])->find();
	    		$order_goods_info=array();
	    		$youhui_price=0;
	    		foreach($order_info_s as $key=>$value){
	    			$order_good=$order_goods->where('order_id='.$value['order_id'])->select();
	    			$order_goods_info=array_merge($order_goods_info,$order_good);
	    			$youhui_price_s=get_coupon_price($value['buyer_id'],$value['coupon']);
	    			$youhui_price=$youhui_price+$youhui_price_s;
	    		}
	    	}elseif($order_info_d){
	    		$order_info=$order_info_d;
	    		$order_goods_info=$order_goods->where('order_id='.$order_info_d['order_id'])->select();
	    		$youhui_price=get_coupon_price($order_info_d['buyer_id'],$order_info_d['coupon']);
		    }

	    	$this->assign('order_goods_info',$order_goods_info);
		    $this->assign('order_info',$order_info);
		    $this->assign('order_num',$order_num);
		    $this->assign('youhui_price',$youhui_price);
		    $this->display();
	    }
    	
    }
    
    function collect_shop(){
    	$users_shopcollect=M('users_shopcollect');
    	$uid=session('user_id');
    	$count=$users_shopcollect->where('user_id='.$uid)->count();
		$Page = new \Think\Page ($count,12); // 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
		$show = $Page->show(); // 分页显示输出
		$rs_shop=$users_shopcollect
		->field('yt_shop.title,yt_shop.id,yt_shop.price,yt_shop.image,yt_users_shopcollect.id as cid')
		->join('yt_shop ON yt_shop.id = yt_users_shopcollect.shop_id','left')
		->where('yt_users_shopcollect.user_id='.$uid)
		->order('yt_users_shopcollect.addtime desc')
		->limit($Page->firstRow.','.$Page->listRows)
		->select();
		$this->assign('rs_shop',$rs_shop);
		$this->assign('page',$show);
    	$this->display();
    }
    function del_collect_shop(){
    	$where['user_id']=session('user_id');
    	$where['id']=I('get.id');
    	$users_shopcollect=M('users_shopcollect');
    	$rs_shop=$users_shopcollect->where($where)->delete();
    	$this->redirect('user/collect_shop');
    }
    
    function collect_store(){
    	$users_storecollect=M('users_storecollect');
    	$uid=session('user_id');
    	$count=$users_storecollect->where('user_id='.$uid)->count();
		$Page = new \Think\Page ($count,12); // 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
		$show = $Page->show(); // 分页显示输出
		$rs_store=$users_storecollect
				->field('yt_store.title,yt_store.id,yt_users_storecollect.id as sid,yt_store_template.portrait')
				->join('yt_store ON yt_store.id = yt_users_storecollect.shore_id','left')
				->join('yt_store_template ON yt_store_template.store_id = yt_users_storecollect.shore_id','left')
				->where('yt_users_storecollect.user_id='.$uid)
				->limit($Page->firstRow.','.$Page->listRows)
				->order('yt_users_storecollect.addtime desc')
				->select();
		$this->assign('rs_store',$rs_store);
		$this->assign('page',$show);
    	$this->display();
    }
    function del_collect_store(){
    	$where['user_id']=session('user_id');
    	$where['id']=I('get.id');
    	$users_storecollect=M('users_storecollect');
    	$users_storecollect->where($where)->delete();
    	$this->redirect('user/collect_store');
    }
    
    //取消订单
    function close_order(){
    	$order_cn=I('get.order_cn');
    	$order=M('order');
    	$order_info_s=$order->where('order_cn='.$order_cn)->select();
	    $order_info_d=$order->where('order_sn='.$order_cn)->find();
    	if($order_info_s){
    		$flag=true;
    		foreach($order_info_s as $key=>$value){
    			$status=get_order_status($value['order_sn'],'10');
    			if($status){
		    		$rs=$order->where('order_sn='.$value['order_sn'])->setField('order_state','0');
			    	if(!$rs){
			    		$flag=false;
			    	}
		    	}else{
		    		$flag=false;
		    	}
    		}
    		if($flag){
	    		$this->success('订单取消成功','',3);
	    	}else{
	    		$this->error('订单取消失败','',3);
	    	}
    	}elseif($order_info_d){
    		$status=get_order_status($order_info_d['order_sn'],'10');
    		if($status){
	    		$rs=$order->where('order_sn='.$order_info_d['order_sn'])->setField('order_state','0');
		    	if($rs){
		    		$this->success('订单取消成功','',3);
		    	}else{
		    		$this->error('订单取消失败','',3);
		    	}
	    	}else{
	    		$this->error('订单取状态不正确,请刷新！！','',3);
	    	}
	    }
		    
		    
    	
    	
    	
    }
    
    //确认收货订单
    function confirm_order(){
    	$order_id=I('post.order_id');
    	$order=M('order');
    	$order_info=$order->find($order_id);
    	$status=get_order_status($order_info['order_sn'],'30');
    	
    	if($status){
    		$data['order_state']='40';
    		$data['finnshed_time']=time();
    		$rs=$order->where('order_id='.$order_id)->save($data);
    		if($rs){
              	 	//收货代言通知
				$uid=$order_info['buyer_id'];
                $order_add_time=$order_info['add_time'];
		        $user_info=M('users')->find($uid);
			
				if($user_info['wx_h5openid']){
					$openid=$user_info['wx_h5openid'];
					$url='https://m.58daiyan.com/user/daiyan.html';
					$keyword1=date('Y年m月d日  H:i',$order_add_time);
					$keyword2=$order_info['order_sn'];
					send_info_daiyan($openid,$url,$keyword1,$keyword2);
				}
	    		$message['code']=1;
	    		$message['message']='确认收货成功';
	    		$this->ajaxReturn($message);
	    		
	    	}else{
	    		$message['code']=0;
	    		$message['message']='确认收货失败';
	    		$this->ajaxReturn($message);
	    	}
    	}else{
    		$message['code']=0;
	    	$message['message']='订单取状态不正确,请刷新！！';
	    	$this->ajaxReturn($message);
    	}
    	
    }
    //第一次评价
    function reviewcommodity(){
    	$order_goods=M('order_goods');
    	$id=I('get.id');
    	$shop_list=$order_goods->where("order_id=$id")->select();
    	$this->assign('shop_list',$shop_list);
    	$this->display();
    }
    
    function addgoodsevaluate(){
    	$goodsEvaluate=json_decode($_POST['goodsEvaluate'],true);
    	$order_id=I('post.order_id');
    	$flag=true;
    	$uid=session('user_id');
    	$userinfo=M('users')->find($uid);
    	$order_goods_evaluate=M('order_goods_evaluate');
    	
    	foreach($goodsEvaluate as $key=>$value){
    		$data=array();
    		$data['order_id']=$order_id;
    		$data['goods_id']=$value['order_goods_id'];
    		$data['uid']=$uid;
    		$data['content']=$value['content'];
    		$data['addtime']=time();
    		$data['image']=$value['imgs'];
    		$data['member_name']=$userinfo['username'];
    		if($value['is_anonymous']){
    			$data['is_anonymous']=1;
    		}else{
    			$data['is_anonymous']=0;
    		}
    		$data['scores']=$value['scores'];
    		
    		$rs=$order_goods_evaluate->add($data);
    		if(!$rs){
    			$flag=false;
    		}
    		aver_shop($value['order_goods_id']);
    		
    	}
    	if($flag){
    		$order_data['order_id']=$order_id;
    		$order_data['evaluation_state']='1';
    		$order=M('order');
    		$rs=$order->save($order_data);
    		if(!$rs){
    			$flag=false;
    		}
    	}
    	if($flag){
    		$this->ajaxReturn(1);
    	}else{
    		$this->ajaxReturn(0);
    	}
    	
    }
    //追加评论
	function reviewagain(){
    	$order_goods=M('order_goods');
    	$id=I('get.id');
    	$shop_list=$order_goods->where("order_id=$id")->select();
    	$this->assign('shop_list',$shop_list);
    	$this->display();
    }
    
    function addgoodsevaluateagain(){
    	$goodsEvaluate=json_decode($_POST['goodsEvaluate'],true);
    	$order_id=I('post.order_id');
    	$flag=true;
    	
    	$order_goods_evaluate=M('order_goods_evaluate');
    	
    	foreach($goodsEvaluate as $key=>$value){
    		$data=array();
    		$map['order_id']=$order_id;
    		$map['goods_id']=$value['order_goods_id'];
    		
    		$data['again_content']=$value['content'];
    		$data['again_addtime']=time();
    		$data['again_image']=$value['imgs'];
    		
    		
    		$rs=$order_goods_evaluate->where($map)->save($data);
    		if(!$rs){
    			$flag=false;
    		}
    	
    		
    	}
    	if($flag){
    		$order_data['order_id']=$order_id;
    		$order_data['evaluation_state']='2';
    		$order=M('order');
    		$rs=$order->save($order_data);
    		if(!$rs){
    			$flag=false;
    		}
    	}
    	if($flag){
    		$this->ajaxReturn(1);
    	}else{
    		$this->ajaxReturn(0);
    	}
    }
    
    
    function evaluate(){
    	$order_goods_evaluate=M('order_goods_evaluate');
    	$uid=session('user_id');
    	$where_evaluate['uid']=$uid;
    	$where_evaluate['is_show']=1;
    	$evaluate_count=$order_goods_evaluate->where($where_evaluate)->count();
    
    	$this->assign('evaluate_count',$evaluate_count);
	    $Page       = new \Think\Page($evaluate_count,6);// 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
	    $show = $Page->show();// 分页显示输出
	  	$evaluate_list=$order_goods_evaluate->where($where_evaluate)->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select();
    	$this->assign('evaluate_list',$evaluate_list);
    	$this->assign('evaluate_page',$show);
    	$this->display();
    }
    function bonus(){
    	$coupon=M('coupon');
    	$uid=session('user_id');
    	
    	$coupon_list=$coupon
    			->field('yt_coupon_type.*')
    			->join('yt_coupon_type on yt_coupon_type.coupon_type_id =yt_coupon.coupon_type_id')
    			->where("yt_coupon.uid=$uid")
    			->select();
    	
    	$this->assign('coupon_list',$coupon_list);
    	$this->display();
    }
  
   function daiyan_bouns(){
    	$invoice=get_web_invoice();
    	
    	$daiyan=M('daiyan');
    	$uid=session('user_id');
		
    	$coupon_list=$daiyan
    			->field('yt_daiyan.*,yt_shop.image,yt_shop.title,yt_shop.dikouquan')
    			->join('yt_shop on yt_shop.id =yt_daiyan.shop_id')
    			->where("yt_daiyan.uid=$uid")
    		   ->select();
       $this->assign('coupon_list',$coupon_list);
       $this->display();
    }
    
    
    function refunddetail(){
    	$order_id=I('get.order_id');
    	$order_shopid=I('get.order_shopid');
    	$order=M('order');
    	$order_goods=M('order_goods');
    	$order_info=$order->find($order_id);
    	$ordergood_info=$order->find($order_shopid);
    	
    	$this->assign('ordergood_info',$ordergood_info);
    	$this->assign('order_info',$order_info);
    	$this->display();
    }
    
    function refunddetail_save(){
    	$order_id=I('post.order_id');
    	$order=M('order');
    	$order_info=$order->find($order_id);
    	$time=time()+60*60*24*7;
    	if($_POST&&$order_info['order_state']>10&&$order_info['finnshed_time']<$time){
    		$data['refund_state']='1';
    		$data['refund_amount']=I('post.refund_require_money');
    		$data['refund_reason']=I('post.refund_reason');
    		$data['refund_type']=I('post.refund_type');
    		$data['order_id']=I('post.order_id');
    		$data['refund_time']=time();
    		$rs=$order->save($data);
    		if($rs){
    			$this->ajax_r(1,'','提交成功');
    		}else{
    			$this->ajax_r(0,'','提交失败');
    		}
    	}else{
    		$this->ajax_r(0,'','订单信息错误');
    	}
    }
    
     function get_orderlogistics(){
	  	if($_POST){
	  		$order_id=I('post.order_id');
	  		$order=M('order');
	  		$order_info=$order->find($order_id);
	  		$result=getOrderTracesByJson($order_info['shipping_company_id'],$order_info['shipping_code'],'1304146','f0e280a8-d7b0-470a-b1bd-8d4a9584a78e','http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx');
	  		$this->ajaxReturn($result);
	  	}
	 }
	 
	 function refunddetail_update(){
	 	if($_POST){
	 		$data['refund_shipping_code']=I('post.wuliu_number');
	 		$data['refund_shipping_company_id']=I('post.wuliu_express');
	 		$data['refund_shipping_name']=I('post.wuliu_express_name');
	 		$data['order_id']=I('post.order_id');
	 		$order=M('order');
	 		$rs=$order->save($data);
	 		if($rs){
    			$this->ajax_r(1,'','提交成功');
    		}else{
    			$this->ajax_r(0,'','提交失败');
    		}
	 	}
	 }
	 
	 function back(){
	 	$order=M('order');
	 	$uid=session('user_id');
	 	$count=$order->where("buyer_id=$uid and refund_state>0")->count();
	 	$Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
	    $show = $Page->show();// 分页显示输出
	    $order_list=$order->where("buyer_id=$uid and refund_state>0")->order('order_id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
	 	$this->assign('order_list',$order_list);
	 	$this->assign('count',$count);
	 	$this->assign('page',$show);
	 	$this->display();
	 }
	 function order_success(){
	 	$order=$_GET['order'];
	 	$this->success('支付成功','/user/order_info/order/'.$order,5);
	 }
	 function ali(){
	 	$uid=session('user_id');
	 	if($_POST){
	 		$data=I('post.');
	 		$code=$data['code'];
	 		if($code==session('moblie_ali_code')){
	 			$info['id']=$uid;
	 			$info['ali_number']=$data['ali_number'];
	 			$info['ali_name']=$data['ali_name'];
	 			$rs=M('users')->save($info);
	 			if($rs){
	 				session('moblie_ali_code',null);
		 			$this->ajaxReturn(1);
		 		}else{
		 			$this->ajaxReturn(0);
		 		}
	 		}else{
	 			$this->ajaxReturn(2);
	 		}
	 	}else{
	 		$this->display();
	 	}
	 	
	 	
	 }
	 function withdrawal(){
	 	$uid=session('user_id');
	 	$userinfo=$this->userinfo;
	 	if($userinfo['ali_number']==null||$userinfo['ali_name']==null){
	 		$this->error('请先完善提现账号','/user/ali');
	 	}
	 	$users_log=M('users_log');
	 	$count=$users_log->where("uid=$uid")->count();
	 	$Page       = new \Think\Page($count,8);// 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
	    $show = $Page->show();// 分页显示输出
	 	$rs=$users_log->where("uid=$uid")->limit($Page->firstRow.','.$Page->listRows)->order('id desc')->select();
	 	$this->assign('rs',$rs);
	 	$this->assign('page',$show);
	 	$this->assign('count',$count);
	 	$this->display();
	 }
	 
	 function get_money(){
	 	$uid=session('user_id');
	 	$users_log=M('users_log');
	 	$users_getmoney=M('users_getmoney');
	 	$users=M('users');
	 	$users->startTrans();
	 	$users_getmoney->startTrans();
	 	$users_log->startTrans();
	 	$data=I('post.');
	 	$get_web_invoice=$this->$get_web_invoice;
		$userinfo=M('users')->find($uid);
		
	 	if($data['tx_money']>$userinfo['money']){
	 		$this->ajaxReturn(2);
	 	}
	 	if($data['tx_money']<$get_web_invoice['web_tixian_user']){
	 		$this->ajaxReturn(3);
	 	}
	 	$log['uid']=$uid;
	 	$log['addtime']=time();
	 	$log['money']=$data['tx_money'];
	 	$log['type']=0;
	 	$log['other']='用户提现';
	 	$log['money_type']=3;
	 	$log_rs=$users_log->add($log);
	 	if($log_rs){
	 		$info['uid']=$uid;
		 	$info['money']=$data['tx_money'];
		 	$info['order_num']=$this->build_order_no();
		 	$info['time']=time();
		 	$info['status']=0;
		 	$info['type']=1;
		 	$info['log_id']=$log_rs;
		 	$rs_getmoney=$users_getmoney->add($info);
		 	if($rs_getmoney){
		 		$rs=$users->where('id='.$uid)->setDec('money',$data['tx_money']); 
		 		
		 		if($rs){
		 			$users->commit();
				 	$users_getmoney->commit();
				 	$users_log->commit();
		 			$this->ajaxReturn(1);
		 		}else{
		 			$users->rollback();
				 	$users_getmoney->rollback();
				 	$users_log->rollback();
		 			$this->ajaxReturn(0);
		 		}
		 	}else{
		 		$this->ajaxReturn($users_getmoney->_sql());
		 	}
	 	}else{
	 		$this->ajaxReturn($log);
	 	}
	 	
	 	
	 	
	 	
	 }
	 
	public function build_order_no()
    {
        $no = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        //检测是否存在
        $db = M('users_getmoney');
        $info = $db->where(array('order_num'=>$no))->find();
        (!empty($info)) && $no = $this->build_order_no();
        return $no;
        
    }
    
    public function daiyan(){
    	$order_goods=M('order_goods');
    	$uid=session('user_id');
    	$count=$order_goods
    		->join('yt_order ON yt_order_goods.order_id = yt_order.order_id','left')
    		->where("yt_order_goods.recommend_id=$uid and yt_order.order_state>'10'")
    		->count();
    	$Page       = new \Think\Page($count,8);// 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
	    $show = $Page->show();// 分页显示输出
    	$rs=$order_goods
    		->join('yt_order ON yt_order_goods.order_id = yt_order.order_id','left')
    		->field("yt_order.buyer_name,yt_order.add_time,yt_order.order_state,yt_order.refund_state,yt_order_goods.*")
    		->where("yt_order_goods.recommend_id=$uid and yt_order.order_state>'10'")
    		->limit($Page->firstRow.','.$Page->listRows)
    		->order('yt_order_goods.rec_id desc')
    		->select();
    	$this->assign('page',$show);
    	$this->assign('count',$count);
    	$this->assign('rs',$rs);
    	$this->display();
    } 
    
    public function daiyan_shop(){
   		
		$uid=session('user_id');
		$html_angel=M('angel')->where("uid=$uid")->select();
    	$count=M('order_goods')
    		->field('yt_shop.title,yt_shop.image,yt_shop.price,yt_shop.redenvelope,yt_shop.id')
    		->join('yt_order ON yt_order_goods.order_id = yt_order.order_id','left')
    		->join('yt_shop ON yt_order_goods.goods_id = yt_shop.id','left')
            ->where("(yt_order.order_state='40' and yt_order.refund_state=0 and yt_order.buyer_id=$uid) or (yt_order.order_state='20' and yt_order.refund_state=0 and yt_order.buyer_id=$uid and yt_order.order_type='2')")
            ->group('yt_order_goods.goods_id')
    		->count();
		$Page       = new \Think\Page($count,8);// 实例化分页类 传入总记录数
		$Page->setConfig('header','条记录');
	    $Page->setConfig('prev','上一页');
	    $Page->setConfig('next','下一页');
	    $show = $Page->show();// 分页显示输出	
    	$rs=M('order_goods')
    		->field('yt_shop.title,yt_shop.image,yt_shop.price,yt_shop.redenvelope,yt_shop.envelope_type,yt_shop.envelope_product_id,yt_shop.id')
    		->join('yt_order ON yt_order_goods.order_id = yt_order.order_id','left')
    		->join('yt_shop ON yt_order_goods.goods_id = yt_shop.id','left')
    		->where("(yt_order.order_state='40' and yt_order.refund_state=0 and yt_order.buyer_id=$uid) or (yt_order.order_state='20' and yt_order.refund_state=0 and yt_order.buyer_id=$uid and yt_order.order_type='2')")
    		->group('yt_order_goods.goods_id')
			->limit($Page->firstRow.','.$Page->listRows)
    		->select();
    	//print_r(M('order_goods')->getLastSql());
    	$store_html_status=false;	
    	$type_html_status=false;	
		foreach($html_angel as $key=>$value){
			if($value['type']==2){$store_html_status=true;}
            if($value['type']==3){$type_html_status=true;}
        }
    	$this->assign('store_html_status',$store_html_status);
    	$this->assign('type_html_status',$type_html_status);
    	$this->assign('page',$show);
    	$this->assign('count',$count);
    	$this->assign('html_angel',$html_angel);
    	$this->assign('rs',$rs);
    	$this->display();
    }
	
	public function weixin_login(){
		
		$AppID=C('wx_login.WEIXIN_APP_KEY');
		$AppSecret=C('wx_login.WEIXIN_APP_SECRET');
	
		$uid=session('user_id');
		if($uid){
			$callback='https://m.58daiyan.com/user/weixin_return/uid/'.$uid; //回调地址
		}else{
			$callback='https://m.58daiyan.com/user/weixin_return'; //回调地址
		}
		
		//微信登录
		//-------生成唯一随机串防CSRF攻击
		$state  = md5(uniqid(rand(), TRUE));
		$callback = urlencode($callback);
		$wxurl = "https://open.weixin.qq.com/connect/qrconnect?appid=".$AppID."&redirect_uri=".$callback."&response_type=code&scope=snsapi_login&state=".$state."#wechat_redirect";
		header("Location: $wxurl");
		
	}
	
	public function oauth_login(){
		$token=I('get.token');
		if($token=='0000'){
			$this->error('该账户已被绑定，不可合并','/user/bduser');
		}
		if($token){
			$rs=M('users')->where('out_login="'.$token.'"')->find();
			if(!$rs){
				$this->error('token不存在，请重新登陆','/user/login');
			}
			$nowtime=time();
			$cha=$nowtime-$rs['out_time'];
			if($cha<30){
				$new_rs['out_login']=null;
				$new_rs['out_time']=null;
				$new_rs['id']=$rs['id'];
				M('users')->save($new_rs);
				session('user_id',$rs['id']);
				session('user_name',$rs['username']);
				session('user_pic',$rs['user_pic']);
				session('login_time',$rs['login_time']);
				$this->success('登陆成功','/user/center');
			}else{
				$this->error('token失效请重新登陆','/user/login');
			}
			
		}
		
	}
	
	
    public function qqlogin(){
		$appid=C('qq_login.QQ_APP_KEY');
		$scope='TencentLogin';
		$callback='http://www.58daiyan.com/user/qq_login';
        $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
		$login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" 
			. $appid . "&redirect_uri=" . urlencode($callback)
			. "&state=" . $_SESSION['state']
			. "&scope=".$scope;
		header("Location:$login_url");
    }
	
	 public function qq_login(){
		$appid=C('qq_login.QQ_APP_KEY');
		$appkey=C('qq_login.QQ_APP_SECRET');
		$callback='http://www.58daiyan.com/user/qq_login';
		 $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
            . "client_id=" . $appid. "&redirect_uri=" . urlencode($callback)
            . "&client_secret=" . $appkey. "&code=" . $_REQUEST["code"];

        $response = file_get_contents($token_url);
        if (strpos($response, "callback") !== false)
        {
            $lpos = strpos($response, "(");
            $rpos = strrpos($response, ")");
            $response  = substr($response, $lpos + 1, $rpos - $lpos -1);
            $msg = json_decode($response);
            if (isset($msg->error))
            {
                echo "<h3>error:</h3>" . $msg->error;
                echo "<h3>msg  :</h3>" . $msg->error_description;
                exit;
            }
        }else{
			$params = array();
			parse_str($response, $params);

			//debug
			//print_r($params);
			$graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params["access_token"];

			$str  = file_get_contents($graph_url);
			if (strpos($str, "callback") !== false)
			{
				$lpos = strpos($str, "(");
				$rpos = strrpos($str, ")");
				$str  = substr($str, $lpos + 1, $rpos - $lpos -1);
			}

			$user = json_decode($str,true);
			
			
			if (isset($user['error']))
			{
				echo "<h3>error:</h3>" . $user['error'];
				echo "<h3>msg  :</h3>" . $user['error_description'];
				exit;
			}elseif(session('user_id')==null){
				$userinfo=M('users')->where("qq_openid='".$user["openid"]."'")->find();
				if(!$userinfo){
					$get_user_info = "https://graph.qq.com/user/get_user_info?"
						. "access_token=" . $params['access_token']
						. "&oauth_consumer_key=" . $appid
						. "&openid=" . $user["openid"]
						. "&format=json";

					$info = file_get_contents($get_user_info);
					$arr = json_decode($info, true);
					if($arr['nickname']){
						$youke['username']=$arr['nickname'];
						$youke['qq_name']=$arr['nickname'];
						$youke['password']="8888888";
						$youke['ishidden']=1;
						$youke['addtime']=time();
						$youke['user_pic']=$arr['figureurl_qq_2'];
						$youke['login_time']=date('Y-m-d H:i:s',time());
						$youke['sex']=0;
						$youke['qq_openid']=$user["openid"];
						$youke['type']=1;
						$youke_id=M('users')->add($youke);
						session('user_id',$youke_id);
						session('user_name',$youke['username']);
						session('user_pic',$youke['user_pic']);
						session('login_time',$youke['login_time']);
					}
				}else{
					//已绑定
					session('user_id',$userinfo['id']);
					session('user_name',$userinfo['username']);
					session('user_pic',$userinfo['user_pic']);
					session('login_time',$userinfo['login_time']);
					//更新登录时间
					$date_time=date('Y-m-d H:i:s', time());
					$login_info['id']=$userinfo['id'];
					$login_info['login_time']=$date_time;
					M('users')->save($login_info);
					
					//添加cookie 购物车
					$cart_array = cookie('cart_array');
					$cart_array = json_decode($cart_array,true);
					foreach($cart_array as $key => $v){
						addcart($userinfo['id'],$v['shop_id'],$v['sku_id'],$v['num']);
					}
					cookie('cart_array',null);
				}
				echo "<script>window.opener.location.href='/user/center'</script>";	
				echo "<script>window.close();</script>";
			
				

				
			}else{
				//绑定
				$uid=session('user_id');
				$user_info=M('users')->find($uid);
				$user['qq_openid']=$user["openid"];
				$userinfo=M('users')->where("qq_openid='".$user["openid"]."'")->find();
				if($userinfo){
					if($userinfo['phone']&&$user_info['phone']){
						echo "<script>alert('该账户已被绑定，不可合并');</script>";	
						echo "<script>window.close();</script>";
						
					}else{
						$this->assign('openid',$user["openid"]);
						$this->display();
					}
					
					
				}else{
					$get_user_info = "https://graph.qq.com/user/get_user_info?"
						. "access_token=" . $params['access_token']
						. "&oauth_consumer_key=" . $appid
						. "&openid=" . $user["openid"]
						. "&format=json";

					$info = file_get_contents($get_user_info);
					$arr = json_decode($info, true);
					$user['qq_openid']=$user["openid"];
					$user['id']=session('user_id');
					$user['qq_name']=$arr['nickname'];
					M('users')->save($user);
					echo "<script>window.opener.location.href='/user/bduser'</script>";	
					echo "<script>window.close();</script>";
				}
			}
			
		
		}

        
    }
	
	public function qq_qjbd(){
		$openid=I('post.openid');
		$uid=session('user_id');
		$is_bd=M('users')->where("qq_openid='".$openid."'")->find();
		if($is_bd){
			$user_info=M('users')->find($uid);
			if($is_bd['phone']&&$user_info['phone']){
				$msg['code']=0;
				$msg['msg']='该微信账户已被绑定，不可合并';
			}else{
				//qq合并
				$data['qq_name']=$is_bd['qq_name'];
				$data['qq_openid']=$openid;
				if($is_bd['phone']){
					if($is_bd['wb_openid']==null&&$user_info['wb_openid']){
						$data['wb_openid']=$user_info['wb_openid'];
						$data['wb_name']=$user_info['wb_name'];
					}
					if($is_bd['wx_openid']==null&&$user_info['wx_openid']){
						$data['wx_openid']=$user_info['wx_openid'];
						$data['wx_name']=$user_info['wx_name'];
					}
					$data['id']=$is_bd['id'];
					$deleid=$user_info['id'];
				}else{
					if($is_bd['wb_openid']&&$user_info['wb_openid']==null){
						$data['wb_openid']=$is_bd['wb_openid'];
						$data['wb_name']=$is_bd['wb_name'];
					}
					if($is_bd['wx_openid']&&$user_info['wx_openid']==null){
						$data['wx_openid']=$is_bd['wx_openid'];
						$data['wx_name']=$is_bd['wx_name'];
					}
					$data['id']=$user_info['id'];
					$deleid=$is_bd['id'];
				}
				$rs=M('users')->save($data);
				if($rs){
					M('users')->delete($deleid);
					//更新登陆
					$new_user_info=M('users')->find($data['id']);
					session('user_id',$new_user_info['id']);
					session('user_name',$new_user_info['username']);
					session('user_pic',$new_user_info['user_pic']);
					session('login_time',$new_user_info['login_time']);
					$msg['code']=1;
					$msg['msg']='QQ绑定成功';
				}else{
					$msg['code']=0;
					$msg['msg']='QQ绑定失败';
				}
			}
			
		}else{
			$data['id']=$uid;
			$data['qq_openid']=$openid;
			$rs=M('users')->save($data);
			if($rs){
				$msg['code']=1;
				$msg['msg']='QQ绑定成功';
			}else{
				$msg['code']=0;
				$msg['msg']='QQ绑定失败';
			}
		}
		$this->ajaxReturn($msg);
	}
	
	public function weibo(){
		session_start();
		vendor('Sinaweibo.Saetv2');
		//注意\
		$o = new \SaeTOAuthV2( C('wb_login.WEIBO_APP_KEY') , C('wb_login.WEIBO_APP_SECRET') );
                 
                //url中不能缺少code
		if(isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = C('wb_login.WEIBO_PC_URL');
			try {
				//生成access token
				$token = $o->getAccessToken('code', $keys ) ;
		 
			} catch (OAuthException $e) {
				//echo 1;die;
			}
		}
 
		if ($token) {
			$c = new \SaeTClientV2( C('wb_login.WEIBO_APP_KEY') , 
			C('wb_login.WEIBO_APP_SECRET') , $token['access_token'] );
			$ms  = $c->home_timeline(); // done
			$uid_get = $c->get_uid();
			$uid = $uid_get['uid'];
			$user_message = $c->show_user_by_id($uid);//根据ID获取用户等基本信息
			$wb_openid=$user_message['idstr'];
	
			if(session('user_id')==null){
				$userinfo=M('users')->where("wb_openid='".$wb_openid."'")->find();
				if($userinfo){
					//已绑定
					session('user_id',$userinfo['id']);
					session('user_name',$userinfo['username']);
					session('user_pic',$userinfo['user_pic']);
					session('login_time',$userinfo['login_time']);
					//更新登录时间
					$date_time=date('Y-m-d H:i:s', time());
					$login_info['id']=$userinfo['id'];
					$login_info['login_time']=$date_time;
					M('users')->save($login_info);
					
					//添加cookie 购物车
					$cart_array = cookie('cart_array');
					$cart_array = json_decode($cart_array,true);
					foreach($cart_array as $key => $v){
						addcart($userinfo['id'],$v['shop_id'],$v['sku_id'],$v['num']);
					}
					cookie('cart_array',null);
					$this->success('登陆成功','/user/center');
				}else{
					//不存在创建游客账号,不是主动注销
					$youke['username']=$user_message['screen_name'];
					$youke['wb_name']=$user_message['screen_name'];
					$youke['password']="8888888";
					$youke['ishidden']=1;
					$youke['addtime']=time();
					$youke['user_pic']=$user_message['avatar_hd'];
					$youke['login_time']=date('Y-m-d H:i:s',time());
					$youke['sex']=0;
					$youke['wb_openid']=$user_message['idstr'];
					$youke['type']=1;
					$youke_id=M('users')->add($youke);
					session('user_id',$youke_id);
					session('user_name',$youke['username']);
					session('user_pic',$youke['user_pic']);
					session('login_time',$youke['login_time']);
					$this->success('登陆成功','/user/center');
				}
			}else{
				$uid=session('user_id');
				$user_info=M('users')->find($uid);
				$userinfo=M('users')->where("wb_openid='".$wb_openid."'")->find();
				if($userinfo){
					if($userinfo['phone']&&$user_info['phone']){
						$this->success('该账户已被绑定，不可合并','/user/bduser');
					}else{
						$this->redirect('user/wb_qjbd',array('openid'=>$wb_openid));
					}
					
				}else{
					//直接绑定
					$user['wb_openid']=$wb_openid;
					$user['wb_name']=$user_message['screen_name'];
					$user['id']=session('user_id');
					M('users')->save($user);
					$this->redirect('user/bduser');
				}
			}
		} else {
			$this->success('配置错误','/user/login');
		}
	}
	function wb_qjbd(){
		if($_POST){
			$openid=I('post.openid');
			$uid=session('user_id');
			$is_bd=M('users')->where("wb_openid='".$openid."'")->find();
			if($is_bd){
				$user_info=M('users')->find($uid);
				if($is_bd['phone']&&$user_info['phone']){
					$msg['code']=0;
					$msg['msg']='该微博账户已被绑定，不可合并';
				}else{
					//qq合并
					$data['wb_name']=$is_bd['wb_name'];
					$data['wb_openid']=$openid;
					if($is_bd['phone']){
						if($is_bd['qq_openid']==null&&$user_info['qq_openid']){
							$data['qq_openid']=$user_info['qq_openid'];
							$data['qq_name']=$user_info['qq_name'];
						}
						if($is_bd['wx_openid']==null&&$user_info['wx_openid']){
							$data['wx_openid']=$user_info['wx_openid'];
							$data['wx_name']=$user_info['wx_name'];
						}
						$data['id']=$is_bd['id'];
						$deleid=$user_info['id'];
					}else{
						if($is_bd['qq_openid']&&$user_info['qq_openid']==null){
							$data['qq_openid']=$is_bd['qq_openid'];
							$data['qq_name']=$is_bd['qq_name'];
						}
						if($is_bd['wx_openid']&&$user_info['wx_openid']==null){
							$data['wx_openid']=$is_bd['wx_openid'];
							$data['wx_name']=$is_bd['wx_name'];
						}
						$data['id']=$user_info['id'];
						$deleid=$is_bd['id'];
					}
					$rs=M('users')->save($data);
					if($rs){
						M('users')->delete($deleid);
						//更新登陆
						$new_user_info=M('users')->find($data['id']);
						session('user_id',$new_user_info['id']);
						session('user_name',$new_user_info['username']);
						session('user_pic',$new_user_info['user_pic']);
						session('login_time',$new_user_info['login_time']);
						$msg['code']=1;
						$msg['msg']='微博绑定成功';
					}else{
						$msg['code']=0;
						$msg['msg']='微博绑定失败';
					}
				}
				$this->ajaxReturn($msg);
			}
			
		}else{
			$openid=I('get.openid');
			$this->assign('openid',$openid);
			$this->display();
		}
		
	}
	function bduser(){
		$uid=session('user_id');
		$user_info=M('users')->find($uid);
		$this->assign('user_info',$user_info);
		$this->display();
	}
	
	function bd_phone(){
		$this->display();
	}
	public function register_validate2(){
		$data=I('get.');
		$users=M('users');
		$moblie=$data['mobile'];
		$rs=$users->where('phone="'.$moblie.'" and ishidden=1')->find();
		if($rs){
			$this->ajax_r(1,'','该帐号已注册');
		}else{
			$this->ajax_r(0,'','');
		}
		
	}
	public function phone_bd(){
		$phone=I('post.phone');
		$password=I('post.pass');
		$sms_captcha=I('post.code');
		$is_phone=M('users')->where("phone='".$phone."' and ishidden=1")->find();
		$uid=session('user_id');
		$y_userinfo=M('users')->find($uid);
	
		if($sms_captcha==session('bd_moblie_code')){
			if($is_phone){
				$uid=session('user_id');
				$user_info=M('users')->find($uid);
				$newdata['id']=$is_phone['id'];
				$newdata['password']=passport_encrypt($password,'wnsc');
				if($y_userinfo['wx_openid']){
					$newdata['wx_openid']=$y_userinfo['wx_openid'];
					$newdata['wx_name']=$y_userinfo['wx_name'];
				}
				if($y_userinfo['wb_openid']){
					$newdata['wb_openid']=$y_userinfo['wb_openid'];
					$newdata['wb_name']=$y_userinfo['wb_name'];
				}
				if($y_userinfo['qq_openid']){
					$newdata['qq_openid']=$y_userinfo['qq_openid'];
					$newdata['qq_name']=$y_userinfo['qq_name'];
				}
				
				$new_rs=M('users')->save($newdata);
				if($new_rs){
					M('users')->delete($uid);
					session('user_id',$is_phone['id']);
				}
			}else{
				$newdata['id']=$uid;
				$newdata['password']=passport_encrypt($password,'wnsc');
				$newdata['phone']=$phone;
				$new_rs=M('users')->save($newdata);
			}
			if($new_rs){
				$msg['code']=1;
				$msg['msg']='手机绑定成功';
			}else{
				$msg['code']=0;
				$msg['msg']='手机绑定失败';
			}
		}else{
			$msg['code']=2;
			$msg['msg']='验证码错误';
		}
		
		$this->ajaxReturn($msg);
	}
  	public function help_info(){
		//获取文章
		$id=I('get.id');
		$info=M('article_posts')->find($id);
		$this->assign('info',$info);
		//获取分类
		$term=M('article_terms')->where('parent=2')->select();
		foreach($term as $key=>$value){
			$list=M('article_posts')->where('trem_id="'.$value['term_id'].'"')->limit('20')->select();
			$term[$key]['list']=$list;
		}
		$this->assign('term',$term);
		$this->display();
	}
  public function help(){
		//获取文章
		$id=I('get.id');
		$info=M('article_posts')
          		->join('yt_article_terms on yt_article_terms.term_id = yt_article_posts.trem_id' )
            	->where('yt_article_terms.parent=2')
            	->order('yt_article_posts.id asc')->find();
    
		$this->redirect('user/help_info',array('id'=>$info['id']));
	}
	
}
?>
